using Microsoft.Win32;
using System.Runtime.InteropServices;
using Windows.Devices.Enumeration;

namespace 新连接蓝牙音频设备音量调节器
{
    public partial class Form1 : Form
    {
        // 不再使用固定常量，改为使用音量滑动条的当前值
        private readonly HashSet<string> _knownDevices = new HashSet<string>();
        private DeviceWatcher? _deviceWatcher;
        private bool _isMonitoring = false;
        
        // 保存窗口最小化前的尺寸和位置
        private Rectangle _minimizedBounds = Rectangle.Empty;
        // 保存窗口最小化前的状态
        private FormWindowState _minimizedState = FormWindowState.Normal;


        public Form1() : this(false)
        {
        }
        
        public Form1(bool isStartup)
        {
            InitializeComponent();
            
            // 设置音量滑动条事件
            volumeTrackBar.ValueChanged += VolumeTrackBar_ValueChanged;
            
            // 设置按钮事件
            _startButton.Click += ToggleMonitoring;
            clearButton.Click += (s, e) => _logTextBox.Clear();
            debugButton.Click += DebugInfo;
            
            // 绑定系统托盘事件
            notifyIcon1.MouseClick += NotifyIcon_MouseClick;
            exitToolStripMenuItem.Click += ExitToolStripMenuItem_Click;
            
            // 设置窗口最小化行为
            this.Resize += Form1_Resize;
            
            // 设置帮助按钮事件
            helpButton.Click += ShowHelpDialog;
            
            // 设置开机启动复选框事件
            startupCheckBox.CheckedChanged += StartupCheckBox_CheckedChanged;
            
            // 初始化开机启动状态
            InitializeStartupSetting();
            
            LogMessage("应用程序已启动，准备就绪");
            
            // 如果是开机启动，则自动开始监听并最小化窗口
            if (isStartup)
            {
                LogMessage("💻 检测到开机启动，自动开始监听并最小化窗口");
                this.WindowState = FormWindowState.Minimized;
                // 延迟启动监听，确保窗口最小化后再开始
                Task.Run(async () =>
                {
                    await Task.Delay(1000); // 等待1秒确保窗口最小化完成
                    this.Invoke(new Action(() => ToggleMonitoring(this, EventArgs.Empty)));
                });
            }
            else
            {
                LogMessage("点击『开始监听』按钮启动设备监控");
            }
        }

        private void VolumeTrackBar_ValueChanged(object? sender, EventArgs e)
        {
            // 更新音量值标签
            volumeValueLabel.Text = $"{volumeTrackBar.Value}%";
            
            // 记录音量变更
            //LogMessage($"音量设置已更新: {volumeTrackBar.Value}%");
        }

        private void LogMessage(string message)
        {
            InvokeIfRequired(() => UpdateLogDisplay(message));
        }

        private void UpdateLogDisplay(string message)
        {
            string timestamp = DateTime.Now.ToString("HH:mm:ss");
            
            // 使用RichTextBox的彩色文本功能
            _logTextBox.SelectionStart = _logTextBox.TextLength;
            _logTextBox.SelectionLength = 0;
            
            // 设置时间戳颜色
            _logTextBox.SelectionColor = Color.Gray;
            _logTextBox.AppendText($"[{timestamp}] ");
            
            // 根据emoji类型设置不同颜色
            Color textColor = Color.FromArgb(30, 30, 30);
            
            // 检测消息中的emoji并设置相应颜色
            if (message.Contains("🚀") || message.Contains("✅") || message.Contains("🎧"))
            {
                // 成功/设备相关的emoji使用蓝色
                textColor = Color.Blue;
            }
            else if (message.Contains("❌") || message.Contains("⏹"))
            {
                // 错误/停止相关的emoji使用红色
                textColor = Color.Red;
            }
            else if (message.Contains("🔧") || message.Contains("📡") || message.Contains("🔍"))
            {
                // 调试/监控相关的emoji使用绿色
                textColor = Color.Green;
            }
            else if (message.Contains("ℹ️") || message.Contains("📊") || message.Contains("📴"))
            {
                // 信息/状态相关的emoji使用橙色
                textColor = Color.Orange;
            }
            
            // 设置消息文本颜色
            _logTextBox.SelectionColor = textColor;
            _logTextBox.AppendText($"{message}\r\n");
            
            _logTextBox.ScrollToCaret();
        }

        // 通用的Invoke帮助方法
        private void InvokeIfRequired(Action action)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }
        }

        // 带返回值的通用Invoke帮助方法
        private T InvokeIfRequired<T>(Func<T> func)
        {
            if (this.InvokeRequired)
            {
                return (T)this.Invoke(func);
            }
            else
            {
                return func();
            }
        }

        private async void ToggleMonitoring(object? sender, EventArgs e)
        {
            if (_isMonitoring)
            {
                // 当前正在监听，需要停止监听
                try
                {
                    _deviceWatcher?.Stop();
                    _deviceWatcher = null;
                    UpdateUIControls(false);

                    LogMessage("⏹ 设备监听服务已停止");
                }
                catch (Exception ex)
                {
                    LogMessage($"❌ 停止监听失败: {ex.Message}");
                }
            }
            else
            {
                // 当前未监听，需要开始监听
                try
                {
                    LogMessage("🚀 正在启动设备监听服务...");

                    // 检查Windows.Devices.Enumeration是否可用
                    await CheckDeviceEnumerationAvailability();

                    // 初始化已知设备列表
                    await InitializeKnownDevices();

                    // 创建设备监视器并注册所有事件
                    _deviceWatcher = DeviceInformation.CreateWatcher(DeviceClass.AudioRender);
                    _deviceWatcher.Added += DeviceWatcher_Added;
                    _deviceWatcher.Updated += DeviceWatcher_Updated;
                    _deviceWatcher.Removed += DeviceWatcher_Removed;
                    _deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
                    _deviceWatcher.Stopped += DeviceWatcher_Stopped;
                    
                    // 启动监视器
                    _deviceWatcher.Start();

                    UpdateUIControls(true);

                    LogMessage("✅ 设备监听服务已启动");
                    LogMessage("📡 正在等待新蓝牙音频设备连接...");
                    
                    // 启动状态监控定时器
                    StartStatusMonitoring();
                }
                catch (Exception ex)
                {
                    LogMessage($"❌ 启动监听失败: {ex.Message}");
                    UpdateUIControls(false);
                }
            }
        }

        private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
        {
            try
            {
                //LogMessage($"📱 检测到新音频设备: {deviceInfo.Name} (ID: {deviceInfo.Id.Substring(0, Math.Min(50, deviceInfo.Id.Length))}...)");
                
                if (!IsBluetoothAudioDevice(deviceInfo))
                {
                    return;
                }

                string deviceKey = deviceInfo.Id;
                if (_knownDevices.Contains(deviceKey))
                {
                    return;
                }

                // 新设备连接
                _knownDevices.Add(deviceKey);
                LogMessage($"🎧 检测到新蓝牙音频设备: {deviceInfo.Name}");

                // 延迟确保设备完全初始化
                await Task.Delay(500);

                // 设置音量
                SetVolumeToTarget(deviceInfo);
                LogMessage($"✅ 已为 '{deviceInfo.Name}' 设置音量为 {GetCurrentVolume()}%");

                // 播放提示音（使用通用的InvokeHelper方法）
                InvokeIfRequired(() => System.Media.SystemSounds.Beep.Play());
            }
            catch (Exception ex)
            {
                LogMessage($"❌ 处理新设备时出错: {ex.Message}");
            }
        }

        private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            LogMessage($"🔄 设备信息更新: {deviceInfoUpdate.Id}");
        }

        private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            string deviceKey = deviceInfoUpdate.Id;
            if (_knownDevices.Contains(deviceKey))
            {
                _knownDevices.Remove(deviceKey);
                LogMessage($"📴 设备已断开连接");
            }
        }

        private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
        {
            LogMessage("✅ 设备枚举完成，监视器正在持续监听新设备...");
        }

        private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
        {
            if (_isMonitoring)
            {
                LogMessage("⚠️ 设备监视器意外停止");
                UpdateUIControls(false);
            }
        }

        private async Task InitializeKnownDevices()
        {
            try
            {
                LogMessage("正在扫描现有蓝牙音频设备...");
                var devices = await DeviceInformation.FindAllAsync(DeviceClass.AudioRender);
                int bluetoothCount = 0;

                foreach (var device in devices)
                {
                    if (IsBluetoothAudioDevice(device))
                    {
                        _knownDevices.Add(device.Id);
                        bluetoothCount++;
                        LogMessage($"📋 已识别现有设备: {device.Name}");
                    }
                }
                LogMessage($"✅ 已初始化 {bluetoothCount} 个现有蓝牙音频设备");
            }
            catch (Exception ex)
            {
                LogMessage($"❌ 初始化设备列表失败: {ex.Message}");
            }
        }

        private bool IsBluetoothAudioDevice(DeviceInformation device)
        {
            try
            {
                string name = device.Name ?? "";
                string id = device.Id ?? "";

                // 更全面的蓝牙标识检查
                bool isBluetooth = name.Contains("Bluetooth", StringComparison.OrdinalIgnoreCase) ||
                                  name.Contains("蓝牙", StringComparison.OrdinalIgnoreCase) ||
                                  name.Contains("BT", StringComparison.OrdinalIgnoreCase) ||
                                  name.Contains("Hands-Free", StringComparison.OrdinalIgnoreCase) ||
                                  name.Contains("Handsfree", StringComparison.OrdinalIgnoreCase) ||
                                  name.Contains("免提", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("Bluetooth", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("BTHENUM", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("BTHHF", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("BTHAVRCP", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("BTHA2DP", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("BTHPORT", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("HFP", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("A2DP", StringComparison.OrdinalIgnoreCase) ||
                                  id.Contains("AVRCP", StringComparison.OrdinalIgnoreCase);

                // 更全面的音频设备标识检查
                bool isAudio = device.Kind == DeviceInformationKind.DeviceInterface ||
                              name.Contains("Audio", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("音频", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Sound", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("声音", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Headset", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Headphone", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("耳机", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Earphone", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Earbud", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Speaker", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("扬声器", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("Microphone", StringComparison.OrdinalIgnoreCase) ||
                              name.Contains("麦克风", StringComparison.OrdinalIgnoreCase) ||
                              id.Contains("Audio", StringComparison.OrdinalIgnoreCase);

                // 如果设备名称或ID包含蓝牙标识，则认为是蓝牙设备
                // 同时检查是否是音频设备
                if (isBluetooth && isAudio)
                {
                    LogMessage($"🔍 识别为蓝牙音频设备: {name}");
                    return true;
                }

                // 特殊处理：如果设备名包含"Hands-Free"且是音频设备，也认为是蓝牙设备
                if ((name.Contains("Hands-Free", StringComparison.OrdinalIgnoreCase) || 
                     name.Contains("Handsfree", StringComparison.OrdinalIgnoreCase) ||
                     name.Contains("免提", StringComparison.OrdinalIgnoreCase)) && isAudio)
                {
                    LogMessage($"🔍 识别为免提蓝牙音频设备: {name}");
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                LogMessage($"❌ 设备识别出错: {ex.Message}");
                return false;
            }
        }

        private void SetVolumeToTarget(DeviceInformation deviceInfo)
        {
            try
            {
                LogMessage($"🔊 正在为设备 '{deviceInfo.Name}' 设置音量...");
                
                // 获取当前音量值（线程安全）
                int currentVolume = GetCurrentVolume();
                
                // 优先使用Core Audio API设置音量
                SetVolumeViaCoreAudio(currentVolume, deviceInfo);
                LogMessage("✅ 使用Core Audio API设置音量成功");
            }
            catch (Exception ex)
            {
                LogMessage($"⚠️ Core Audio音量设置失败: {ex.Message}");
                
                // 立即尝试快速备用方法，不等待
                Task.Run(() => 
                {
                    try
                    {
                        LogMessage("🔄 立即尝试快速备用音量设置方法...");
                        int currentVolume = GetCurrentVolume();
                        SetVolumeFallback(currentVolume);
                    }
                    catch (Exception fallbackEx)
                    {
                        LogMessage($"❌ 快速备用方法也失败: {fallbackEx.Message}");
                    }
                });
                
                // 同时尝试重试Core Audio方法
                Task.Run(async () => 
                {
                    await Task.Delay(200); // 短暂延迟后重试
                    try
                    {
                        LogMessage("🔄 重试Core Audio音量设置...");
                        int currentVolume = GetCurrentVolume();
                        SetVolumeViaCoreAudio(currentVolume, deviceInfo);
                        LogMessage("✅ Core Audio重试成功");
                    }
                    catch (Exception retryEx)
                    {
                        LogMessage($"❌ Core Audio重试失败: {retryEx.Message}");
                    }
                });
            }
        }
        
        private int GetCurrentVolume()
        {
            return InvokeIfRequired(GetVolumeValue);
        }

        private int GetVolumeValue()
        {
            return volumeTrackBar.Value;
        }

        private void SetVolumeViaCoreAudio(int volume, DeviceInformation deviceInfo)
        {
            const int maxRetries = 3;
            IMMDeviceEnumerator? enumerator = null;
            IMMDevice? device = null;
            IAudioEndpointVolume? endpointVolume = null;
            
            try
            {
                for (int attempt = 1; attempt <= maxRetries; attempt++)
                {
                    try
                    {
                        LogMessage($"🔊 尝试为设备 '{deviceInfo.Name}' 设置音量 (第{attempt}次尝试)...");
                        
                        enumerator = new MMDeviceEnumerator() as IMMDeviceEnumerator;
                        if (enumerator == null)
                            throw new Exception("无法创建音频设备枚举器");

                        // 尝试获取默认设备（兼容性）
                        int hr = enumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out device);
                        if (hr != 0)
                        {
                            if (attempt < maxRetries)
                            {
                                LogMessage($"⚠️ 获取默认音频端点失败，{attempt}/{maxRetries}次尝试");
                                System.Threading.Thread.Sleep(100 * attempt); // 递增延迟
                                continue;
                            }
                            throw new Exception($"获取默认音频端点失败 (HRESULT: 0x{hr:X8})");
                        }

                        var IID_IAudioEndpointVolume = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A");
                        hr = device.Activate(IID_IAudioEndpointVolume, 0, IntPtr.Zero, out object endpointVolumeObj);
                        if (hr != 0)
                        {
                            if (attempt < maxRetries)
                            {
                                LogMessage($"⚠️ 激活音频端点音量接口失败，{attempt}/{maxRetries}次尝试");
                                System.Threading.Thread.Sleep(100 * attempt);
                                continue;
                            }
                            throw new Exception($"激活音频端点音量接口失败 (HRESULT: 0x{hr:X8})");
                        }

                        endpointVolume = endpointVolumeObj as IAudioEndpointVolume;
                        if (endpointVolume != null)
                        {
                            float volumeLevel = Math.Clamp(volume / 100.0f, 0.0f, 1.0f);
                            hr = endpointVolume.SetMasterVolumeLevelScalar(volumeLevel, Guid.Empty);

                            if (hr != 0)
                            {
                                if (attempt < maxRetries)
                                {
                                    LogMessage($"⚠️ 设置音量失败，{attempt}/{maxRetries}次尝试");
                                    System.Threading.Thread.Sleep(100 * attempt);
                                    continue;
                                }
                                throw new Exception($"设置音量失败 (HRESULT: 0x{hr:X8})");
                            }
                            
                            LogMessage($"✅ 音量设置成功: {volume}% (第{attempt}次尝试)");
                            return; // 成功则退出
                        }
                        else
                        {
                            throw new Exception("音频端点音量接口转换失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (attempt == maxRetries)
                        {
                            LogMessage($"❌ Core Audio设置失败 (最终尝试): {ex.Message}");
                            throw new Exception($"Core Audio设置失败: {ex.Message}");
                        }
                        else
                        {
                            LogMessage($"⚠️ Core Audio设置失败 (第{attempt}次尝试): {ex.Message}");
                            System.Threading.Thread.Sleep(100 * attempt); // 递增延迟
                        }
                    }
                }
            }
            finally
            {
                // 确保COM对象被正确释放
                if (endpointVolume != null)
                {
                    try { Marshal.ReleaseComObject(endpointVolume); }
                    catch { /* 忽略释放异常 */ }
                }
                if (device != null)
                {
                    try { Marshal.ReleaseComObject(device); }
                    catch { /* 忽略释放异常 */ }
                }
                if (enumerator != null)
                {
                    try { Marshal.ReleaseComObject(enumerator); }
                    catch { /* 忽略释放异常 */ }
                }
            }
        }

        private void SetVolumeFallback(int volume)
        {
            try
            {
                IntPtr hwnd = GetDesktopWindow();
                if (hwnd == IntPtr.Zero)
                    throw new Exception("无法获取桌面窗口句柄");

                // 取消静音（确保设备未静音）
                SendMessageW(hwnd, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_MUTE);
                System.Threading.Thread.Sleep(50);
                SendMessageW(hwnd, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_MUTE);

                // 快速设置到目标音量（使用更高效的算法）
                // 先快速设置到大致位置，再微调
                int targetVolume = Math.Clamp(volume, 0, 100);
                
                // 快速设置到目标音量附近
                if (targetVolume > 50)
                {
                    // 如果目标音量大于50%，先快速增加到80%
                    for (int i = 0; i < 30; i++)
                    {
                        SendMessageW(hwnd, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_UP);
                    }
                }
                else
                {
                    // 如果目标音量小于等于50%，先快速降低到20%
                    for (int i = 0; i < 30; i++)
                    {
                        SendMessageW(hwnd, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_DOWN);
                    }
                }
                
                System.Threading.Thread.Sleep(100); // 短暂等待系统响应
                
                // 微调到精确目标音量
                int estimatedCurrent = targetVolume > 50 ? 80 : 20;
                int fineTuneSteps = Math.Abs(targetVolume - estimatedCurrent) / 2;
                
                for (int i = 0; i < fineTuneSteps; i++)
                {
                    if (targetVolume > estimatedCurrent)
                        SendMessageW(hwnd, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_UP);
                    else
                        SendMessageW(hwnd, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_DOWN);
                    
                    System.Threading.Thread.Sleep(5); // 更短的延迟
                }

                LogMessage($"✅ 备用音量设置完成: {volume}%");
            }
            catch (Exception ex)
            {
                throw new Exception($"备用音量设置失败: {ex.Message}");
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (_isMonitoring)
            {
                var result = MessageBox.Show("设备监听正在运行，确定要退出吗？",
                    "确认退出",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
            }

            ToggleMonitoring(this, EventArgs.Empty);
            StopStatusMonitoring();
            base.OnFormClosing(e);
        }

        private async Task CheckDeviceEnumerationAvailability()
        {
            try
            {
                LogMessage("🔍 检查设备枚举功能可用性...");
                
                // 测试设备枚举功能
                var devices = await DeviceInformation.FindAllAsync(DeviceClass.AudioRender);
                LogMessage($"✅ 设备枚举功能正常，发现 {devices.Count} 个音频设备");
                
                // 显示所有设备信息用于调试
                foreach (var device in devices)
                {
                    //LogMessage($"📋 设备: {device.Name} | ID: {device.Id.Substring(0, Math.Min(30, device.Id.Length))}...");
                }
            }
            catch (Exception ex)
            {
                LogMessage($"❌ 设备枚举功能检查失败: {ex.Message}");
                throw new Exception("设备枚举功能不可用，请确保系统支持Windows.Devices.Enumeration");
            }
        }

        private System.Windows.Forms.Timer? _statusTimer;
        
        private void StartStatusMonitoring()
        {
            _statusTimer = new System.Windows.Forms.Timer();
            _statusTimer.Interval = 5000; // 5秒检查一次
            _statusTimer.Tick += (s, e) =>
            {
                if (_isMonitoring && _deviceWatcher != null)
                {
                    //LogMessage("💓 设备监视器状态: 运行正常");
                }
            };
            _statusTimer.Start();
        }

        private void StopStatusMonitoring()
        {
            _statusTimer?.Stop();
            _statusTimer?.Dispose();
            _statusTimer = null;
        }

        private async void DebugInfo(object? sender, EventArgs e)
        {
            try
            {
                // 使用通用的InvokeHelper方法处理跨线程调用
                InvokeIfRequired(() => {
                    LogMessage("🐛 === 调试信息开始 ===");
                    LogMessage($"📊 当前状态: {(_isMonitoring ? "监听中" : "未监听")}");
                    LogMessage($"📋 已知设备数量: {_knownDevices.Count}");
                    LogMessage($"🔍 设备监视器状态: {(_deviceWatcher?.Status.ToString() ?? "未初始化")}");
                    // 显示所有音频设备
                    LogMessage("🎧 当前系统音频设备列表:");
                });

                
                
                var devices = await DeviceInformation.FindAllAsync(DeviceClass.AudioRender);
                
                int bluetoothCount = 0;
                foreach (var device in devices)
                {
                    bool isBluetooth = IsBluetoothAudioDevice(device);
                    string status = isBluetooth ? "✅ 蓝牙设备" : "❌ 非蓝牙设备";
                    
                    if (isBluetooth) bluetoothCount++;
                    
                    // 使用通用的InvokeHelper方法处理跨线程调用
                    InvokeIfRequired(() => {
                        LogMessage($"   {status}: {device.Name}");
                        LogMessage($"     ID: {device.Id.Substring(0, Math.Min(50, device.Id.Length))}...");
                    });
                }
                
                // 使用通用的InvokeHelper方法处理跨线程调用
                InvokeIfRequired(() => {
                    LogMessage($"📊 总计: {devices.Count} 个音频设备，其中 {bluetoothCount} 个蓝牙设备");
                    LogMessage("🐛 === 调试信息结束 ===");
                });
            }
            catch (Exception ex)
            {
                // 使用通用的InvokeHelper方法处理跨线程调用
                InvokeIfRequired(() => LogMessage($"❌ 获取调试信息失败: {ex.Message}"));
            }
        }
        
        // 系统托盘事件处理
        private void Form1_Resize(object? sender, EventArgs e)
        {
            // 当窗口最小化时，隐藏到系统托盘
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                notifyIcon1.ShowBalloonTip(1000, "蓝牙音量控制器", "程序已最小化到系统托盘", ToolTipIcon.Info);
            }
            else
            {
                // 窗口正常显示时，确保任务栏也显示
                this.ShowInTaskbar = true;
                // 保存最小化前的窗口状态和位置
                _minimizedState = this.WindowState;
                _minimizedBounds = this.Bounds;
            }
        }
        
        private void NotifyIcon_MouseClick(object? sender, MouseEventArgs e)
        {
            // 鼠标左键单击：还原窗口
            if (e.Button == MouseButtons.Left)
            {
                // 如果窗口当前是最小化状态，则恢复窗口
                if (this.WindowState == FormWindowState.Minimized)
                {
                    // 先显示窗口
                    this.ShowInTaskbar = true;
                    this.Activate();
                    
                    // 恢复最小化前的窗口状态和位置
                    if (!_minimizedBounds.IsEmpty)
                    {
                        this.Bounds = _minimizedBounds;
                    }
                    this.WindowState = _minimizedState;
                }
            }
        }
        
        private void ExitToolStripMenuItem_Click(object? sender, EventArgs e)
        {
            // 退出程序，与点击窗口关闭按钮逻辑一致
            this.Close();
        }

        // 帮助按钮点击事件处理
        private void ShowHelpDialog(object? sender, EventArgs e)
        {
            // 获取程序集版本信息
            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            string versionText = version != null ? $"v{version.Major}.{version.Minor}.{version.Build}" : "未知版本";
            
            // 从程序集属性中读取作者和版权信息
            string author = "未知作者";
            string copyright = "未知版权";
            
            try
            {
                // 获取程序集属性
                var assembly = System.Reflection.Assembly.GetExecutingAssembly();
                
                // 获取公司属性（作者）
                var companyAttributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), false);
                if (companyAttributes.Length > 0)
                {
                    author = ((System.Reflection.AssemblyCompanyAttribute)companyAttributes[0]).Company;
                }
                
                // 获取版权属性
                var copyrightAttributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyCopyrightAttribute), false);
                if (copyrightAttributes.Length > 0)
                {
                    copyright = ((System.Reflection.AssemblyCopyrightAttribute)copyrightAttributes[0]).Copyright;
                }
            }
            catch (Exception ex)
            {
                // 如果读取失败，使用默认值
                author = "luzhishen666";
                copyright = "Copyright © 2025";
                Console.WriteLine($"读取程序集信息失败: {ex.Message}");
            }
            
            // 显示程序用法介绍对话框
            string helpText = $@"蓝牙音频设备音量调节器 - 使用说明

📄 程序信息：
• 版本：{versionText}
• 作者：{author}
• 版权：{copyright}

📋 程序功能：
• 自动检测新连接的蓝牙音频设备
• 自动将新设备音量设置为指定值
• 实时监控设备连接状态
• 支持系统托盘最小化
• 开机自动启动功能

🎯 使用方法：
1. 设置目标音量：使用滑动条调整期望的音量百分比
2. 开始监听：点击『开始监听』按钮启动设备监控
3. 连接设备：连接新的蓝牙音频设备
4. 自动调节：程序会自动检测新设备并设置音量
5. 停止监听：点击『停止监听』按钮结束监控

⚙️ 注意事项：
• 程序需要管理员权限才能调节系统音量
• 确保蓝牙功能已开启
• 程序最小化后会显示在系统托盘
• 点击系统托盘图标可恢复窗口显示
• 可通过开机启动选项设置程序随系统启动

📞 技术支持：
如遇问题，请检查系统音频设置或重新启动程序";
            
            MessageBox.Show(helpText, "程序使用说明", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        // Windows API
        [DllImport("user32.dll")]
        private static extern IntPtr GetDesktopWindow();

        [DllImport("user32.dll")]
        private static extern IntPtr SendMessageW(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        private const uint WM_APPCOMMAND = 0x319;
        private const int APPCOMMAND_VOLUME_UP = 0xA0000;
        private const int APPCOMMAND_VOLUME_DOWN = 0x90000;
        private const int APPCOMMAND_VOLUME_MUTE = 0x80000;

        // Core Audio COM接口
        [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
        private class MMDeviceEnumerator { }

        [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IMMDeviceEnumerator
        {
            void NotNeeded();
            [PreserveSig]
            int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppDevice);
        }

        [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IMMDevice
        {
            [PreserveSig]
            int Activate([MarshalAs(UnmanagedType.LPStruct)] Guid iid, int dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
        }

        [Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IAudioEndpointVolume
        {
            void RegisterControlChangeNotify(IntPtr notify);
            void UnregisterControlChangeNotify(IntPtr notify);
            [PreserveSig]
            int GetChannelCount(out int channelCount);
            [PreserveSig]
            int SetMasterVolumeLevel(float levelDB, Guid eventContext);
            [PreserveSig]
            int SetMasterVolumeLevelScalar(float level, Guid eventContext);
            [PreserveSig]
            int GetMasterVolumeLevel(out float levelDB);
            [PreserveSig]
            int GetMasterVolumeLevelScalar(out float level);
        }

        private enum EDataFlow
        {
            eRender = 0,
            eCapture = 1,
            eAll = 2
        }

        private enum ERole
        {
            eConsole = 0,
            eMultimedia = 1,
            eCommunications = 2
        }

        // 开机启动功能实现
        private void InitializeStartupSetting()
        {
            try
            {
                // 检查当前是否已设置开机启动
                using (RegistryKey? key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", false))
                {
                    if (key != null)
                    {
                        string appName = "蓝牙音频设备音量调节器";
                        string currentValue = key.GetValue(appName)?.ToString() ?? "";
                        
                        if (!string.IsNullOrEmpty(currentValue) && currentValue.Contains(Application.ExecutablePath))
                        {
                            startupCheckBox.Checked = true;
                            LogMessage("✅ 开机启动已启用");
                        }
                        else
                        {
                            startupCheckBox.Checked = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogMessage($"❌ 检查开机启动设置失败: {ex.Message}");
                startupCheckBox.Checked = false;
            }
        }

        private void StartupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            try
            {
                if (startupCheckBox.Checked)
                {
                    // 启用开机启动
                    using (RegistryKey? key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
                    {
                        if (key != null)
                        {
                            string appName = "蓝牙音频设备音量调节器";
                            string appPath = Application.ExecutablePath ?? "";
                            
                            if (!string.IsNullOrEmpty(appPath))
                            {
                                // 添加启动参数 /startup
                                string startupPath = $"\"{appPath}\" /startup";
                                key.SetValue(appName, startupPath);
                                LogMessage("✅ 已启用开机启动");
                            }
                            else
                            {
                                LogMessage("❌ 应用程序路径为空，无法设置开机启动");
                                startupCheckBox.Checked = false;
                            }
                        }
                        else
                        {
                            LogMessage("❌ 无法访问注册表，请以管理员权限运行程序");
                            startupCheckBox.Checked = false;
                        }
                    }
                }
                else
                {
                    // 禁用开机启动
                    using (RegistryKey? key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
                    {
                        if (key != null)
                        {
                            string appName = "蓝牙音频设备音量调节器";
                            
                            if (key.GetValue(appName) != null)
                            {
                                key.DeleteValue(appName, false);
                                LogMessage("✅ 已禁用开机启动");
                            }
                        }
                        else
                        {
                            LogMessage("❌ 无法访问注册表，请以管理员权限运行程序");
                            startupCheckBox.Checked = true;
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                LogMessage("❌ 权限不足，请以管理员权限运行程序以修改开机启动设置");
                startupCheckBox.Checked = !startupCheckBox.Checked; // 恢复原状态
            }
            catch (Exception ex)
            {
                LogMessage($"❌ 修改开机启动设置失败: {ex.Message}");
                startupCheckBox.Checked = !startupCheckBox.Checked; // 恢复原状态
            }
        }


        /// <summary>
        /// 统一更新UI控件状态的方法
        /// </summary>
        /// <param name="isMonitoring">是否处于监听状态</param>
        private void UpdateUIControls(bool isMonitoring)
        {
            _isMonitoring =  isMonitoring;
            InvokeIfRequired(() => {
                // 根据监听状态设置按钮文本、状态指示器文本和颜色
                if (isMonitoring)
                {
                    _startButton.Text = "⏹ 停止监听";
                    _statusIndicator.Text = "🔴 监听中";
                    _statusIndicator.ForeColor = Color.Red;
                    // 监听状态：使用红色表示敏感行为
                    _startButton.BackColor = Color.Red;
                }
                else
                {
                    _startButton.Text = "▶ 开始监听";
                    _statusIndicator.Text = "🟢 未监听";
                    _statusIndicator.ForeColor = Color.Green;
                    // 非监听状态：使用绿色表示安全状态
                    _startButton.BackColor = Color.ForestGreen;
                }
            });
        }
    }
}